package com.meihua.workflow.global;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.meihua.workflow.constants.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@Configuration
@WebFilter("/*")
public class GlobalFilter implements Filter {
    public static Integer getUserId;
    public static String access_token = null;
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    String [] whiteList=new String[]{"/user/signIn","/excel/**"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter----走拦截器了");
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        for (String uri : whiteList) {
            boolean match = PATH_MATCHER.match(uri, request.getRequestURI());
            if (match){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for(Cookie c : cookies){
                if (Objects.equals(c.getName(), "access_token")){
                    access_token=c.getValue();
                    break;
                }
            }
        }
        if (StrUtil.isNotEmpty(access_token)){
            Long expireTime = (Long)JWTUtil.parseToken(access_token).getPayload("expire_time");
            Long refreshTime = (Long)JWTUtil.parseToken(access_token).getPayload("refresh_time");
            if (expireTime>=System.currentTimeMillis()){
                getUserId= (Integer) JWTUtil.parseToken(access_token).getPayload("user_id");
                filterChain.doFilter(servletRequest,servletResponse);
            }
            else {
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(JSONUtil.toJsonStr(R.error(50014,"TOKEN_EXPIRED")));
            }
            return;
        }
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSONUtil.toJsonStr(R.error(50000,"NEED_LOGIN")));
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
